<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    class="p-4 enter-x"
    :model="formData"
    :rules="getFormRules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
  >
    <FormItem name="username" class="enter-x" :rules="[{ required: true, message: '请填写账号!' }]">
      <Input
        size="large"
        v-model:value="formData.username"
        :placeholder="t('sys.login.userName')"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x" :rules="[{ required: true, message: '请填写密码!' }]">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
      />
    </FormItem>

    <FormItem
      name="captcha"
      label=""
      class="enter-x"
      :rules="[{ required: true, message: '请填写图片验证码!' }]"
    >
      <Input
        size="large"
        :visibilityToggle="false"
        v-model:value="formData.captcha"
        placeholder="图片验证码，点击图片刷新"
        autocomplete="off"
        style="position: relative;"
      >
        <template #prefix>
          <div style="padding-right: 10px">
            <Icon icon="f7:textformat-abc"></Icon>
          </div>
        </template>
        <template #suffix>
          <img
            v-if="captchaRes.img_base64"
            :src="captchaRes.img_base64"
            alt="图片验证码，点击刷新"
            style="width: 30%; height: 32px;position: absolute;right:4px;border-radius: 4px;cursor:pointer;"
            @click.stop="loadImgCode"
          />
        </template>
      </Input>
    </FormItem>

    <!--
  <ARow class="enter-x">
    <ACol :span="12">
      <FormItem>
        &lt;!&ndash; No logic, you need to deal with it yourself &ndash;&gt;
        <Checkbox v-model:checked="rememberMe" size="small">
          {{ t('sys.login.rememberMe') }}
        </Checkbox>
      </FormItem>
    </ACol>
    </ARow>
    -->

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
    </FormItem>
  </Form>
</template>
<script lang="ts" setup>
import {reactive, ref, unref, computed, nextTick} from 'vue';

  import { Checkbox, Form, Input, Row, Col, Button, Divider } from 'ant-design-vue';
  import {
    GithubFilled,
    WechatFilled,
    AlipayCircleFilled,
    GoogleCircleFilled,
    TwitterCircleFilled,
  } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';

  import { useUserStore } from '@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '@/hooks/web/useDesign';
  import {getCaptcha} from "@/api/common";
  //import { onKeyStroke } from '@vueuse/core';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const captchaRes = ref({ img_base64: '' })
  const {createMessage} = useMessage()

  const formData = reactive({
    username: '',
    password: '',
    captcha: '',
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      const userInfo = await userStore.login(formData);
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.username}`,
          duration: 3,
        });
      }
    } catch (error) {
      loadImgCode();
      createMessage.error((error as unknown as Error).message || t('sys.api.networkExceptionMsg'))
    } finally {
      loading.value = false;
    }
  }

  nextTick(() => {
    loadImgCode();
  })

  const loadImgCode = () => {
    nextTick(async () => {
    const { result: { img_base64 } } = await getCaptcha();
    captchaRes.value.img_base64 = img_base64
    })
  }
</script>
